<template>
  <div class="app-container">
    <Transfer
      v-model:target-keys="formState.roleIdList"
      :data-source="dataSource"
      :titles="['未选角色', '已选角色']"
      :render="(item) => item.title"
    />
    <Divider />
    <a-button type="primary" :loading="btnLoading" @click="onSubmit">提交</a-button>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Transfer, Divider } from 'ant-design-vue'
  import { updateUserRole, all, userRole } from '/@/api/sys/role'

  const emit = defineEmits(['onSuccess'])
  const prop = defineProps({
    userId: String,
  })

  onMounted(() => {
    all().then((res) => {
      dataSource.value = res.map((e) => {
        return {
          key: e.id,
          title: e.name,
        }
      })
    })
    userRole(prop.userId).then((res) => {
      formState.value.roleIdList = res.map((e) => e.id)
    })
  })

  const dataSource = ref([])

  const formState = ref<any>({
    userId: prop.userId,
    roleIdList: [],
  })

  const btnLoading = ref(false)

  const onSubmit = () => {
    btnLoading.value = true
    updateUserRole(formState.value)
      .then(() => {
        btnLoading.value = false
        emit('onSuccess')
      })
      .catch(() => (btnLoading.value = false))
  }
</script>
